package org.elanfox.intellicommunity.intellicommunityadmin.controller.base;

import org.elanfox.intellicommunity.common.base.ApiResult;
import org.elanfox.intellicommunity.common.base.ResultCodeEnum;
import org.elanfox.intellicommunity.common.resource.StaticResourceService;
import org.elanfox.intellicommunity.common.resource.base.ResourceVO;
import org.elanfox.intellicommunity.common.utils.RandomUtils;
import org.elanfox.intellicommunity.common.utils.StringUtilsExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author allan
 * @date 12/11/2017
 */
@Controller
@RequestMapping(value = "/resource")
public class ResourceController {
    private static final String IMG_SUFFIX_PATH = "";
    @Autowired
    private StaticResourceService resourceService;

//    @RequestMapping(value = "/upload", method = RequestMethod.POST)
//    @ResponseBody
//    public ApiResult uploadImage(@OperatorId Integer operatorId,
//                                 @RequestParam(value = "img", required = false) MultipartFile file,
//                                 @RequestParam(value = "path", defaultValue = "article") String clientPath
//    ) throws IOException, URISyntaxException {
//        if (operatorId == null || operatorId <= 0) {
//            return ApiResult.resultWith(ResultCodeEnum.NOT_AUTHORITY);
//        }
//        if (StringUtils.isEmpty(clientPath)) {
//            clientPath = "none";
//        }
//        //上传图片
//        if (file != null) {
//            String fileName = file.getOriginalFilename();
//            String prefix = fileName.substring(fileName.lastIndexOf("."));
//            String savePath = MessageFormat.format(VStaticResourceService.IMG, clientPath, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmSS")))
//                    + prefix;
//            Resource resource = resourceService.upload(savePath, file.getInputStream());
//            if (resource != null) {
//                Map<String, String> map = new HashMap<>(1);
//                map.put("url", resource.getURI().toString());
//                map.put("path", resource.getURI().getPath());
//                return ApiResult.resultWith(ResultCodeEnum.SUCCESS, map);
//            }
//        }
//        return ApiResult.resultWith(ResultCodeEnum.ERROR, "请上传图片");
//    }

    /**
     * ueditor获取配置信息使用
     *
     * @param request
     * @param response
     * @param action
     */
//    @RequestMapping("/ueditorDispatch")
//    public void ueditorDispatch(HttpServletRequest request, HttpServletResponse response, String action) {
//        try {
//            request.setCharacterEncoding("utf-8");
//            response.setHeader("Content-Type", "text/html");
//            String rootPath = request.getSession().getServletContext().getRealPath("/") + "resource/ueditor/";
//            if (request.getParameter("action").equals("config")) {
//                request.getRequestDispatcher("/resource/ueditor/jsp/controller.jsp").forward(request, response);
//                return;
//            } else if (action.equals("imageUpload")) {
//                request.getRequestDispatcher("uEditorImage").forward(request, response);
//                return;
//            }
//            ActionEnter actionEnter = new ActionEnter(request, rootPath);
//            String exec = actionEnter.exec();
//
//            response.getWriter().write(exec);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult image(@RequestParam(value = "img", required = false) MultipartFile file) throws IOException, URISyntaxException {
        ResourceVO resourceVO = upload(file, IMG_SUFFIX_PATH);
        Map<String, String> map = new HashMap<>(1);
                map.put("url", resourceVO.getFileUri());
                map.put("path", resourceVO.getFilePath());
        return ApiResult.resultWith(ResultCodeEnum.SUCCESS, map);
    }


//    /**
//     * ueditor上传图片专用
//     *
//     * @param file
//     * @return
//     * @throws IOException
//     * @throws URISyntaxException
//     */
//    @RequestMapping("/uEditorImage")
//    @ResponseBody
//    public JSONObject uEditorImage(MultipartFile file) throws IOException, URISyntaxException {
//        ResourceVO resourceVO = upload(file, IMG_SUFFIX_PATH);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("state", "SUCCESS");
//        jsonObject.put("url", resourceVO.getFileUri());
//        jsonObject.put("title", resourceVO.getFilePath());
//        jsonObject.put("size", file.getSize());
//        jsonObject.put("original", file.getOriginalFilename());
//        jsonObject.put("type", resourceVO.getFilePath().split("\\.")[1]);
//        return jsonObject;
//    }

    private ResourceVO upload(MultipartFile file, String suffixPath) throws IOException, URISyntaxException {
        Date now = new Date();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            throw new FileNotFoundException("未上传任何文件");
        }
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String path = suffixPath + StringUtilsExt.dateFormat(now, "yyyyMMdd") + "/"
                + RandomUtils.randomFlowNo(6) + "." + prefix;
        Resource resource = resourceService.upload(path, file.getInputStream());
        return new ResourceVO(resource.getURI().toString(), path);
    }
}
